package com.atguigu.gmall.common.config.thread;

import com.atguigu.gmall.common.config.thread.properties.AppThreadProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * @author lhh
 * @ClassName AppThreadPoolExecutorConfiguration
 * @date 2022 2022/12/5
 */
@EnableConfigurationProperties({AppThreadProperties.class})
@Slf4j
@Configuration
public class AppThreadPoolAutoConfiguration {
    @Bean
    public ThreadPoolExecutor threadPoolExecutor(AppThreadProperties appThreadProperties){
        return new ThreadPoolExecutor(appThreadProperties.getCorePoolSize(),
                appThreadProperties.getMaximumPoolSize(),
                appThreadProperties.getKeepAliveTime(),
                TimeUnit.MINUTES,
                new LinkedBlockingQueue<>(appThreadProperties.getWorkQueueSize()),
                new ThreadFactory() {
                    int i = 1;
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = new Thread(r); //创建线程，执行任务
                        //给名字
                        thread.setName("核心线程["+ i++ +"]");
                        //1~10
                        thread.setPriority(10); //设置优先级
                        return thread;
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }
}
